<template>
  <base-layout>
    <div class="page-container">
      <!-- 搜索区域 -->
      <a-card class="search-card" :bordered="false">
        <div class="search-header">
          <div class="left">
            <h2>项目搜索</h2>
            <span class="desc">您可以搜索项目名称、所属课程等信息</span>
          </div>
          <div class="search-box">
            <a-input-search
              v-model:value="searchText"
              placeholder="请输入项目名称、课程名称"
              style="width: 360px"
              @search="handleSearch"
              size="large"
            >
              <template #prefix>
                <search-outlined />
              </template>
            </a-input-search>
            <a-button type="primary" size="large" @click="handleCreateProject">
              <template #icon><plus-outlined /></template>
              新增项目
            </a-button>
          </div>
        </div>

        <!-- 分类选择 -->
        <div class="filter-area">
          <div class="filter-item">
            <span class="label">类型：</span>
            <a-radio-group v-model:value="projectType" @change="handleTypeChange" button-style="solid">
              <a-radio-button value="all">全部</a-radio-button>
              <a-radio-button value="course">课程项目</a-radio-button>
              <a-radio-button value="comprehensive">综合项目</a-radio-button>
            </a-radio-group>
          </div>
          <div class="filter-item">
            <span class="label">状态：</span>
            <a-radio-group v-model:value="projectStatus" @change="handleStatusChange" button-style="solid">
              <a-radio-button value="all">全部</a-radio-button>
              <a-radio-button value="pending">待批阅</a-radio-button>
              <a-radio-button value="completed">已完成</a-radio-button>
            </a-radio-group>
          </div>
        </div>
      </a-card>

      <!-- 项目列表 -->
      <a-card class="table-card" :bordered="false">
        <template #title>
          <div class="table-header">
            <span class="title">项目列表</span>
            <span class="desc">共 {{ pagination.total }} 个项目</span>
          </div>
        </template>
        <template #extra>
          <a-button 
            type="primary" 
            danger 
            :disabled="selectedRowKeys.length === 0"
            @click="handleBatchDelete"
          >
            <template #icon><delete-outlined /></template>
            批量删除
          </a-button>
        </template>
        <a-table
          :columns="columns"
          :data-source="projects"
          :loading="loading"
          :pagination="pagination"
          :row-selection="rowSelection"
          @change="handleTableChange"
          :scroll="{ x: 1300 }"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <a-space>
                <a-tooltip title="批阅项目">
                  <a @click="handleView(record)" class="action-link">
                    <file-text-outlined />批阅
                  </a>
                </a-tooltip>
                <a-tooltip title="修改项目">
                  <a @click="handleModify(record)" class="action-link">
                    <edit-outlined />修改
                  </a>
                </a-tooltip>
                <a-tooltip title="删除项目">
                  <a-popconfirm
                    title="确定要删除这个项目吗？"
                    ok-text="确定"
                    cancel-text="取消"
                    @confirm="handleDelete(record)"
                  >
                    <a class="action-link delete">
                      <delete-outlined />删除
                    </a>
                  </a-popconfirm>
                </a-tooltip>
              </a-space>
            </template>
            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ record.status }}
              </a-tag>
            </template>
            <template v-else-if="column.key === 'score'">
              <span :class="{ 'highlight-score': record.score === '100' }">{{ record.score }}</span>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </base-layout>
</template>

<script>
import { ref, onMounted } from 'vue'
import { message, Modal } from 'ant-design-vue'
import BaseLayout from '@/components/layout/BaseLayout.vue'
import {
  SearchOutlined,
  PlusOutlined,
  FileTextOutlined,
  EditOutlined,
  DeleteOutlined
} from '@ant-design/icons-vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { projectApi } from '@/api'
import {getProjectDetail, getProjects} from "@/api/projects.js";

export default {
  name: 'ProjectManage',
  components: {
    BaseLayout,
    SearchOutlined,
    PlusOutlined,
    FileTextOutlined,
    EditOutlined,
    DeleteOutlined
  },
  setup() {
    const router = useRouter()
    const loading = ref(false)
    const projects = ref([])
    const searchText = ref('')
    const projectType = ref('all')
    const projectStatus = ref('all')
    const pagination = ref({
      current: 1,
      pageSize: 10,
      total: 0,
      showQuickJumper: true,
      showSizeChanger: true,
      pageSizeOptions: ['10', '20', '50', '100'],
      showTotal: (total) => `共 ${total} 条记录 第 ${pagination.value.current} / ${Math.ceil(total / pagination.value.pageSize)} 页`
    })
    const selectedRowKeys = ref([])

    const columns = [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id',
        width: 80,
        fixed: 'left'
      },
      {
        title: '项目名称',
        dataIndex: 'name',
        key: 'name',
        width: 200,
        fixed: 'left',
        ellipsis: true
      },
      {
        title: '所属课程',
        dataIndex: 'course',
        key: 'course',
        width: 200,
        ellipsis: true
      },
      {
        title: '类型',
        dataIndex: 'type',
        key: 'type',
        width: 120
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        key: 'createTime',
        width: 180
      },
      {
        title: '批阅时间',
        dataIndex: 'reviewTime',
        key: 'reviewTime',
        width: 180
      },
      {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        width: 150
      },
      {
        title: '分数',
        dataIndex: 'score',
        key: 'score',
        width: 100,
        align: 'center'
      },
      {
        title: '操作',
        key: 'action',
        width: 200,
        fixed: 'right',
        align: 'center'
      }
    ]

    const getStatusColor = (status) => {
      const colors = {
        '系统设计待批阅': 'processing',
        '已完成': 'success',
        '创建项目': 'default'
      }
      return colors[status] || 'default'
    }

    const fetchProjects = async () => {
      try {
        loading.value = true
        const params = {
          page: pagination.value.current,
          pageSize: pagination.value.pageSize,
          keyword: searchText.value,
          type: projectType.value !== 'all' ? projectType.value : undefined,
          status: projectStatus.value !== 'all' ? projectStatus.value : undefined
        }

        const data = await getProjects()
        projects.value = data.content.map(item => ({
          ...item,
          key: item.id
        }))
        pagination.value.total = data.totalElements
      } catch (error) {
        message.error('获取项目列表失败：' + error.message)
      } finally {
        loading.value = false
      }
    }

    const handleSearch = (value) => {
      searchText.value = value
      pagination.value.current = 1
      fetchProjects()
    }

    const handleTypeChange = () => {
      pagination.value.current = 1
      fetchProjects()
    }

    const handleStatusChange = () => {
      pagination.value.current = 1
      fetchProjects()
    }

    const handleCreateProject = () => {
      router.push('/project-create')
    }

    const handleView = async (record) => {
      try {
        router.push({
          path: `/project-review/${record.id}`,
          query: { name: record.name }
        })
      } catch (error) {
        message.error('获取项目详情失败：' + error.message)
      }
    }

    const handleDelete = async (record) => {
      try {
        await projectApi.deleteProject(record.id)
        message.success('删除成功')
        fetchProjects()
      } catch (error) {
        message.error('删除失败')
      }
    }

    const handleModify = (record) => {
      router.push({
        path: `/project-edit/${record.id}`,
        query: { name: record.name }
      })
    }

    const handleTableChange = (pag) => {
      pagination.value.current = pag.current
      pagination.value.pageSize = pag.pageSize
      fetchProjects()
    }

    // 添加表格多选配置
    const rowSelection = {
      selectedRowKeys: selectedRowKeys.value,
      onChange: (keys) => {
        selectedRowKeys.value = keys
      }
    }

    // 批量删除方法
    const handleBatchDelete = async () => {
      if (selectedRowKeys.value.length === 0) {
        return
      }

      try {
        await new Promise((resolve, reject) => {
          Modal.confirm({
            title: '确认删除',
            content: `确定要删除选中的 ${selectedRowKeys.value.length} 个项目吗？`,
            okText: '确定',
            okType: 'danger',
            cancelText: '取消',
            onOk: resolve,
            onCancel: reject
          })
        })

        loading.value = true
        await axios.delete('/api/projects/batch', {
          data: { ids: selectedRowKeys.value }
        })
        
        message.success('批量删除成功')
        selectedRowKeys.value = []
        await fetchProjects()
      } catch (error) {
        if (error) {
          message.error('批量删除失败：' + error.message)
        }
      } finally {
        loading.value = false
      }
    }

    onMounted(() => {
      fetchProjects()
    })

    return {
      loading,
      projects,
      columns,
      pagination,
      searchText,
      projectType,
      projectStatus,
      getStatusColor,
      handleSearch,
      handleTypeChange,
      handleStatusChange,
      handleCreateProject,
      handleView,
      handleDelete,
      handleModify,
      handleTableChange,
      selectedRowKeys,
      rowSelection,
      handleBatchDelete
    }
  }
}
</script>

<style scoped>
.page-container {
  padding: 24px;
  background: #f0f2f5;
  min-height: 100vh;
}

.search-card {
  margin-bottom: 24px;
  border-radius: 8px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.search-header .left {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.search-header h2 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: rgba(0, 0, 0, 0.85);
}

.search-header .desc {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

.search-box {
  display: flex;
  gap: 16px;
}

.filter-area {
  display: flex;
  flex-wrap: wrap;
  gap: 32px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.filter-item .label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.85);
}

.table-card {
  border-radius: 8px;
}

.table-header {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.table-header .title {
  font-size: 16px;
  font-weight: 500;
  color: rgba(0, 0, 0, 0.85);
}

.table-header .desc {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.45);
}

:deep(.ant-table) {
  background: #fff;
}

:deep(.ant-table-pagination) {
  margin: 16px 0;
  justify-content: center;
}

.action-link {
  display: inline-flex;
  align-items: center;
  gap: 4px;
  color: #1890ff;
}

.action-link:hover {
  color: #40a9ff;
}

.action-link.delete {
  color: #ff4d4f;
}

.action-link.delete:hover {
  color: #ff7875;
}

.highlight-score {
  color: #52c41a;
  font-weight: 500;
}

:deep(.ant-table-cell) {
  font-size: 14px;
}

:deep(.ant-radio-group) {
  display: flex;
}

:deep(.ant-radio-button-wrapper) {
  min-width: 88px;
  text-align: center;
}

:deep(.ant-card-extra) {
  margin-left: 16px;
}
</style> 